package com.hi.hiparty.ui.fragment;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.LinearLayout.LayoutParams;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.hi.hiparty.R;
import com.hi.hiparty.entity.Party;
import com.hi.hiparty.ui.MainActivity;
import com.hi.hiparty.ui.widget.PullDownView;
import com.hi.hiparty.ui.widget.PullDownView.OnPullDownListener;
import com.hi.hiparty.util.ApiHelper;
import com.hi.hiparty.util.HttpUtil;
import com.hi.hiparty.util.ImageDownloader;
import com.hi.hiparty.util.StringUtils;
import com.hi.hiparty.util.TimeUtils;

public class PartyListFragment extends SherlockFragment implements OnItemClickListener, OnPullDownListener {

	public static final String TAG = PartyListFragment.class.getSimpleName();

	private static final class Operation {
		public static final int init = 0;
		public static final int refresh = 1;
		public static final int more = 2;
	}

	private static final int page_size = 10;

	private int total = 0;

	private List<Party> partys;

	// private View mEmptyView;

	private PullDownView mPullDownView;

	private ListView mListView;

	private PartyListAdapter adapter;

	private PopupWindow mPartyFilterPopwin;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		long time = System.currentTimeMillis();
		View view = inflater.inflate(R.layout.square_date_list, container, false);

		mPullDownView = (PullDownView) view.findViewById(R.id.party_list);

		mPullDownView.setOnPullDownListener(this);
		mListView = mPullDownView.getListView();
		mListView.setOnItemClickListener(this);

		fetchPartyList(getActivity(), Operation.init, 0, page_size);
		Log.v(TAG, "time cost:" + (System.currentTimeMillis() - time));
		return view;
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		inflater.inflate(R.menu.main_function_nav_menu, menu);
		super.onCreateOptionsMenu(menu, inflater);
		MainActivity mainActivity = (MainActivity) getActivity();
		mainActivity.getSupportActionBar().setTitle(getString(R.string.activity_title_square));
		mainActivity.getSupportActionBar().setDisplayHomeAsUpEnabled(false);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		MainActivity mainActivity = (MainActivity) getActivity();
		switch (item.getItemId()) {
		case R.id.menu_add_party:
			mainActivity.onPubNewParty();
			break;

		case R.id.menu_search:

			break;
		case R.id.menu_edit_user:
			mainActivity.onEditUser();
			break;

		case R.id.menu_show_filter:
			if (null != mPartyFilterPopwin && mPartyFilterPopwin.isShowing()) {
				mPartyFilterPopwin.dismiss();
			} else {
				showFilterPopWin(mainActivity.findViewById(R.id.menu_show_filter));
			}
			break;
		default:
			break;
		}
		return true;
	}

	private void showFilterPopWin(View menuItemView) {
		LayoutInflater mLayoutInflater = LayoutInflater.from(getActivity());
		View filter_popunwindwow = mLayoutInflater.inflate(R.layout.popwin_party_filter, null);
		mPartyFilterPopwin = new PopupWindow(filter_popunwindwow, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		mPartyFilterPopwin.setBackgroundDrawable(new BitmapDrawable());
		mPartyFilterPopwin.setFocusable(true);
		mPartyFilterPopwin.setOutsideTouchable(true);
		mPartyFilterPopwin.setAnimationStyle(R.style.popup_animation);
		mPartyFilterPopwin.showAsDropDown(menuItemView, 0, 10);

		Button mConfirmBtn = (Button) filter_popunwindwow.findViewById(R.id.btn_confirm);
		mConfirmBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

			}
		});

		Button mCancelBtn = (Button) filter_popunwindwow.findViewById(R.id.btn_cancel);
		mCancelBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (null != mPartyFilterPopwin && mPartyFilterPopwin.isShowing()) {
					mPartyFilterPopwin.dismiss();
				}
			}
		});
	}

	public void refresh() {
		fetchPartyList(getActivity(), Operation.refresh, 0, page_size);
	}

	private void fetchPartyList(FragmentActivity activity, int op, int start, int size) {
		new ListPartyTask().execute(op, start, size);
	}

	private class PartyListAdapter extends BaseAdapter {

		@SuppressWarnings("unused")
		private Context mContext;

		private List<Party> mlist;

		private LayoutInflater mInflater;

		@SuppressWarnings("unused")
		private final ImageDownloader imageDownloader = new ImageDownloader();

		public PartyListAdapter(Context context, List<Party> list) {
			super();
			this.mContext = context;
			this.mlist = list;
			this.mInflater = LayoutInflater.from(context);
		}

		@SuppressWarnings("unused")
		public void setList(List<Party> list) {
			this.mlist = list;
		}

		@Override
		public int getCount() {
			return mlist.size();
		}

		@Override
		public Object getItem(int position) {
			return mlist.get(position);
		}

		@Override
		public long getItemId(int position) {
			return mlist.get(position).hashCode();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			Log.d(TAG, "List的item开始getView");
			if (null == mlist || mlist.size() == 0) {
				return null;
			}
			Party party = mlist.get(position);
			View view = mInflater.inflate(R.layout.square_party_item, mListView, false);

			TextView partyTitleTextView = (TextView) view.findViewById(R.id.text_party_title);
			partyTitleTextView.setText(getString(R.string.text_i_want) + party.getTitle());

			TextView partyStartTimeTextView = (TextView) view.findViewById(R.id.text_party_time);
			partyStartTimeTextView.setText(TimeUtils.formatDateTimeForCustomer(party.getStartTime()));

			TextView partyAddressTextView = (TextView) view.findViewById(R.id.text_party_location);
			partyAddressTextView.setText(party.getAddress());

			TextView partyDescTextView = (TextView) view.findViewById(R.id.text_party_desc);
			if (StringUtils.isBlank(party.getDescription())) {
				partyDescTextView.setText("这家伙很懒，什么也没有留下");
			} else {
				partyDescTextView.setText(party.getDescription());
			}

			TextView partyCommentCntTextView = (TextView) view.findViewById(R.id.text_party_comment_count);
			partyCommentCntTextView.setText("99");

			TextView partyIntrCntTextView = (TextView) view.findViewById(R.id.text_party_int_count);
			partyIntrCntTextView.setText("99");

			TextView partyHolderNameTextView = (TextView) view.findViewById(R.id.text_party_holder_name);
			partyHolderNameTextView.setText("莫言");

			return view;
		}

	}

	private class ListPartyTask extends AsyncTask<Integer, Void, Boolean> {

		int op, start, size;

		String error;

		List<Party> mlist;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// mEmptyView.setVisibility(View.VISIBLE);
		}

		@Override
		protected Boolean doInBackground(Integer... params) {
			if (partys != null) {
				return true;
			}
			op = params[0];
			start = params[1];
			size = params[2];
			String url = ApiHelper.API_QUERT_PARTY_ORDERBY_TIME + "/" + start + "/" + size;
			String jsonValue = HttpUtil.GET(url);
			if (null == jsonValue) {
				error = getString(R.string.error_connection);
				return false;
			}
			JSONObject json = null;
			try {
				json = new JSONObject(jsonValue);
				if (1 == json.getInt("success")) {
					JSONArray list = json.getJSONArray("partys");
					if (null == list) {
						error = getString(R.string.error_no_result);
						return false;
					}
					mlist = new ArrayList<Party>();
					for (int i = 0; i < list.length(); i++) {
						JSONObject partyJson = list.getJSONObject(i);
						Party party = new Party();
						party.setUserid(partyJson.getString("userid"));
						party.setPartyid(partyJson.getString("partyid"));
						party.setTitle(partyJson.getString("title"));
						party.setTheme(partyJson.getString("theme"));
						party.setAddress(partyJson.getString("address"));
						party.setDescription(partyJson.getString("description"));
						party.setStartTime(TimeUtils.parseDateTime(partyJson.getString("startTime")));
						if (partyJson.has("endTime")) {
							party.setEndTime(TimeUtils.parseDateTime(partyJson.getString("endTime")));
						}
						party.setUserPos(partyJson.getString("userPos"));
						party.setPartyPos(partyJson.getString("partyPos"));
						mlist.add(party);
					}
					total += list.length();
				}
			} catch (JSONException e) {
				Log.w(TAG, e);
				error = getString(R.string.error_connection);
				return false;
			}
			return true;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			// mEmptyView.setVisibility(View.GONE);
			if (!result) {
				Toast.makeText(getActivity(), error, Toast.LENGTH_LONG).show();
			} else {
				if (null == adapter) {
					adapter = new PartyListAdapter(getActivity(), mlist);
					mListView.setAdapter(adapter);
				} else {
					mListView.setAdapter(adapter);
					adapter.notifyDataSetChanged();
				}
			}
			switch (op) {
			case Operation.init:
				mPullDownView.notifyDidLoad();
				break;

			case Operation.refresh:
				mPullDownView.notifyDidRefresh();
				break;

			case Operation.more:
				mPullDownView.notifyDidMore();
				break;
			default:
				break;
			}
		}
	}

	@Override
	public void onItemClick(AdapterView<?> listview, View view, int position, long id) {
		if (null == listview) {
			return;
		}
		Party party = (Party) listview.getItemAtPosition(position);
		if (null == party) {
			return;
		}
		Activity act = getActivity();
		if (null == act) {
			return;
		}
		OnPartyListItemClickListener listener = null;
		try {
			listener = (OnPartyListItemClickListener) act;
		} catch (ClassCastException e) {
			throw new ClassCastException(act.toString() + " must implement OnPartyListItemClickListener");
		}
		listener.onPartyListItemClick(party);
	}

	public interface OnPartyListItemClickListener {
		public void onPartyListItemClick(Party party);
	}

	@Override
	public void onRefresh() {
		fetchPartyList(getActivity(), Operation.refresh, 0, page_size);
	}

	@Override
	public void onMore() {
		fetchPartyList(getActivity(), Operation.more, total, page_size);
	}

}
